'use strict';

app.controller('summaryCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$filter', '$location', '$timeout', 'lodash', function ($scope, $http, $stateParams, $rootScope, $filter, $location, $timeout, lodash) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    var save = {
        show: true,
        label: "保存",
        func: function () {
            saveProjectPlan();
        }
    }
    var backUrl = {
        show: true,
        label: "返回",
        func: function () {
            $rootScope.backHistory();
        }
    }

    //pdm才可以编辑数据
    if ($rootScope.isUserCanOperateByRole( "pdm")) {
        $scope.settings.btnEle.push(save);
        $scope.settings.btnEle.push(backUrl);
    } else {
        $scope.settings.btnEle.push(backUrl);
    }
    //结束headerElement设置
    setStorage('brdBackUrl', $location.url());

    $scope.info = {
        pdmList: [],    //pdm集合
        pmList: [],    //pm集合
        memberList: [],    //member集合
        sPdmList: "",    //已选择pdm
        sPmList: "",    //已选择pm
        sltMemberItem: "",    //已选择member
        reqList: [],    //获取req集合（保存projectplan时需要）
        memUser: null,
        featureValue: "",
        selectReq: null,
        projectPlanId: $stateParams.id,
        projectPlanInfo: {},   //项目计划详情
        memberThdata: [
            {"thName": "姓名"},
            {"thName": "角色"},
            {"thName": "项目任务数"},
            {"thName": "完成任务数"},
            {"thName": "延迟任务数"},
            {"thName": "活动项目数"},
            {"thName": "总任务数"},
            {"thName": "操作", "isHide": true},
        ],
        memberPage: {"isTrue": false},
        meList: {
            "trIsClick": false,
            "tdName": [
                {"name": "name"},
                {"name": "roleName"},
                {"name": "newTask"},
                {"name": "downTask"},
                {"name": "delayedTask"},
                {"name": "doingTask"},
                {"name": "totalTask"},
                {"name": ""},
            ]
        }
    };

    getProjectPlanDetails();

    //获取项目计划详情
    function getProjectPlanDetails() {
        var url = matrix_product_url + "/projectPlan/getProjectPlans?containFinished=Y&projectPlanId=" + $scope.info.projectPlanId;
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.info.projectPlanInfo = result.data[0];
                $scope.breadcrumb.push('项目计划', $scope.info.projectPlanInfo.projectPlanName);
                getReqList();
                getMemberTaskList(result.data[0]);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //获取req数据集（通过projectPlanId）
    function getReqList() {
        var url = matrix_product_url + "/brdRequirement/getBrdRequirements?withFeatureDesc=0&projectPlanId=" + $scope.info.projectPlanId;
        $http.get(url).success(function (result) {
            if (result.code == "0") {
                $scope.info.reqList = result.data;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //添加负责人(PM)和PDM到团队成员中
    $scope.addItemOfMember = function (item, type) {
        lodash.remove($scope.info.meList.datas, {role: type});
        var currentRole = lodash.findWhere(config_plan_role, {key: type});
        var itemOfMember = lodash.findWhere($scope.info.meList.datas, {account: item.account});
        if (itemOfMember) {
            itemOfMember.role = type;
            itemOfMember.roleName = currentRole.name;
        } else {
            var newItem = {
                name: item.realname,
                account: item.account,
                role: type,
                roleName: currentRole.name,
                delayedTask: "0",
                doingTask: "0",
                downTask: "0",
                newTask: "0",
                totalTask: "0",
            };
            $scope.info.meList.datas.push(newItem);
        }
    };

    //获取成员数据
    function getMemberTaskList(projectPlanDetails) {
        var url = matrix_product_url + "/task/getMemberTaskStats?projectPlanId=" + $scope.info.projectPlanId + "&tokenId=" + getTokenId();
        $http.get(url).success(function (result) {
            $timeout(function () {
                if (result.code == "0") {
                    angular.forEach(result.data, function (data) {
                        var crtMember = lodash.findWhere(config_plan_role, {key: data.role});
                        data.roleName = crtMember ? crtMember.name : data.role;
                    });
                    $scope.info.meList.datas = result.data;
                    getUserList(projectPlanDetails, result.data);
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            },500)

        });
    }

    //获取用户数据集（为pdm,pm,member赋值）
    function getUserList(projectPlanDetails, memberTaskList) {
        var url = beetle_auth_url + "/user/?token_id=" + getTokenId();
        $http.get(url).success(function (result) {
            if (result.success) {
                angular.forEach(result.data, function (data) {
                    data.crtname = data.realname ? data.realname : data.account;
                });
                $scope.info.pdmList = result.data;
                $scope.info.pmList = result.data;
                $scope.info.memberList = angular.copy(result.data);
                $scope.info.sPdmList = lodash.findWhere($scope.info.pdmList, {account: projectPlanDetails.projectPlanPdmAccount});
                $scope.info.sPmList = lodash.findWhere($scope.info.pmList, {account: projectPlanDetails.projectPlanChargerAccount});
                angular.forEach(memberTaskList, function (member) {
                    lodash.remove($scope.info.memberList, {account: member.account});
                });
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //我要加入
    $scope.addMeToMemeberList = function () {
        var info = lodash.findWhere($scope.info.memberList, {account: getUserAccount()});
        if(!info) {
            $rootScope.toasterWarningInfo("当前成员已经存在，不能重复添加！");
            return false;
        }
        $scope.info.sltMemberItem = info;
        $scope.addMemeberToList();
    };

    //添加团队成员
    $scope.addMemeberToList = function () {
        if (!$scope.info.sltMemberItem) {
            $rootScope.toasterWarningInfo("请选择要添加的成员！");
            return false;
        }
        var hasMemeber = lodash.findWhere($scope.info.meList.datas, {account: $scope.info.sltMemberItem.account});
        if (!hasMemeber) {
            var currentRole = lodash.findWhere(config_plan_role, {key: $scope.info.sltMemberItem.role});
            var newItem = {
                name: $scope.info.sltMemberItem.realname,
                account: $scope.info.sltMemberItem.account,
                role: $scope.info.sltMemberItem.role ? $scope.info.sltMemberItem.role : "member",
                roleName: currentRole ? currentRole.name : "成员",
                delayedTask: "0",
                doingTask: "0",
                downTask: "0",
                newTask: "0",
                totalTask: "0",
            };
            $scope.info.meList.datas.push(newItem);
            lodash.remove($scope.info.memberList, {account: $scope.info.sltMemberItem.account});
            $scope.info.sltMemberItem = "";
        } else {
            $rootScope.toasterWarningInfo("该成员已存在！");
        }
    };

    //更新项目计划概述数据
    function saveProjectPlan() {
        var postParams = $scope.info.projectPlanInfo;
        postParams.projectPlanOnlineTime = $filter('date')($scope.info.projectPlanInfo.projectPlanOnlineTime, 'yyyy-MM-dd');
        postParams.projectPlanStartupTime = $filter('date')($scope.info.projectPlanInfo.projectPlanStartupTime, 'yyyy-MM-dd')
        if (postParams.projectPlanOnlineTime <= postParams.projectPlanStartupTime) {
            $rootScope.toasterWarningInfo("上线日期必须大于开始日期！");
            return false;
        }
        postParams.reqIds = [];
        postParams.projectPlanName = trimAll($scope.info.projectPlanInfo.projectPlanName);
        postParams.projectPlanCode = $scope.info.projectPlanInfo.projectPlanCode;
        postParams.reqIds = lodash.pluck($scope.info.reqList, "reqId");
        postParams.projectPlanChargerAccount = $scope.info.sPmList.account;
        postParams.projectPlanChargerRealname = $scope.info.sPmList.account.realname;
        postParams.projectPlanPdmAccount = $scope.info.sPdmList.account;
        postParams.projectPlanPdmRealname = $scope.info.sPdmList.realname;
        postParams.tokenId = getTokenId();
        postParams.projectPlanCreaterAccount = getUserAccount();  //common.js中的方法
        postParams.projectPlanCreaterRealname = getUserName();     //common.js中的方法
        postParams.memebers = JSON.stringify(setRoleArray());

        $rootScope.showPanelLoading();
        var url = matrix_product_url + "/projectPlan/saveProjectPlan";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: {"Content-Type": "application/json"}
        }).success(function (result) {
            if (result.code == "0") {
                $rootScope.toasterSuccessInfo("保存成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $rootScope.hidePanelLoading();
        });
    };

    //设置成员数据格式
    function setRoleArray() {
        var roleArray = [];
        angular.forEach($scope.info.meList.datas, function (member) {
            roleArray.push({
                "account": member.account,
                "realname": member.name,
                "role": (member.role == undefined ? "member" : member.role)
            });
        });
        return roleArray;
    }

    //上传控件
    $timeout(function () {
        initFileInput("sqlFile", ['doc', 'docx', 'txt', 'img', 'tiff', 'vsd', 'jpg', 'png', 'pdf', 'xls', 'xlsx']);
    }, 1000);

    //初始化文件上传控件
    function initFileInput(id, allowedFileExtensions) {
        var input = $("#" + id);
        $scope.info.projectPlanInfo.attachments = [];
        input.fileinput({
            language: 'zh', //设置语言
            uploadUrl: matrix_product_url + '/attachment/uploadFile',
            showUpload: true,
            uploadAsync: true,
            // allowedFileExtensions : ['jpg', 'png','gif'],//接收的文件后缀
            allowedFileExtensions: allowedFileExtensions,//接收的文件后缀
            uploadExtraData: function () {
                return {
                    resourceType: 'PRD'
                };
            }
        }).on("fileuploaded", function (event, data, previewId, index) {
            if (data.response.code != '0') {
                $rootScope.toasterWarningInfo(data.response.desc);
                return false;
            }
            ;
            $scope.$apply(function () {
                $scope.info.projectPlanInfo.attachments.push(data.response.data);
                if ($scope.info.projectPlanInfo.attachmentIds == null) {
                    $scope.info.projectPlanInfo.attachmentIds = [];
                }
                $scope.info.projectPlanInfo.attachmentIds.push(data.response.data.attachmentId);
            });
        });
    };

    //下载
    $scope.downloadFile = function (attachmentId) {
        window.location.href = matrix_product_url + "/attachment/downloadFile?attachmentId=" + attachmentId;
    };

}]);
